/*
 * esp8266.c
 *
 *  Created on: 2019年9月7日
 *      Author: caesar
 */

// esp8266 wifi模块的源文件

#include <string.h>
#include "../lib/ls1c_public.h"
#include "../lib/ls1c_uart.h"
#include "../lib/start.h"
#include "../lib/ls1c_irq.h"
#include "../lib/ls1c_pin.h"
#include "../lib/ls1c_delay.h"

// 串口接收缓存大小，单位字节
#define ESP8266_RECV_BUFF_SIZE          (1024)
#define end "\"}]}&^!"


extern char tems[5];
extern char hums[5];
extern unsigned char firewarn[3];
extern unsigned char poisonwarn[3];

extern unsigned char firewarning,poisonwarning;


// 接收信息
typedef struct
{
    unsigned int recv_len;      // 已经接收到的数据长度，单位字节
    unsigned char buff[ESP8266_RECV_BUFF_SIZE];     // 接收缓存
}esp8266_recv_info_t;
esp8266_recv_info_t esp8266_recv_info = {0};


// esp8266串口信息
ls1c_uart_info_t esp8266_uart_info = {0};


static char table[]={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

void num2char(char *str, float number, uint8_t g, uint8_t l)
{
    uint8_t i;
    int temp = number/1;
    double t2 = 0.0;
    for (i = 1; i<=g; i++)
    {
        if (temp==0)
            str[g-i] = table[0];
        else
            str[g-i] = table[temp%10];
        temp = temp/10;
    }
    *(str+g) = '.';
    temp = 0;
    t2 = number;
    for(i=1; i<=l; i++)
    {
        temp = t2*10;
        str[g+i] = table[temp%10];
        t2 = t2*10;
    }
    *(str+g+l+1) = '\0';
}






/*
 * 串口8的中断处理函数
 * @IRQn 中断号
 * @param 传递给中断处理函数的参数
 */
void esp8266_uart_irqhandler(int IRQn, void *param)
{
    ls1c_uart_t uartx = esp8266_uart_info.UARTx;
    void *uart_base = uart_get_base(uartx);
    unsigned char iir = reg_read_8(uart_base + LS1C_UART_IIR_OFFSET);
    unsigned char data = 0;

    // 判断是否接收超时 或 接收到有效数据
    if ((IIR_RXTOUT & iir) || (IIR_RXRDY & iir))
    {
        // 是，则读取数据，并保存
        while (LSR_RXRDY & reg_read_8(uart_base + LS1C_UART_LSR_OFFSET))
        {
            // 读出一个字节
            data = reg_read_8(uart_base + LS1C_UART_DAT_OFFSET);

            // 判断是否还有空闲空间
            if (ESP8266_RECV_BUFF_SIZE-1 > esp8266_recv_info.recv_len)
            {
                //有空闲空间，则存放到缓存中
                esp8266_recv_info.buff[esp8266_recv_info.recv_len++] = data;
            }
        }

        // 手动增加一个字符串结束符，方便调试时打印字符串
        esp8266_recv_info.buff[esp8266_recv_info.recv_len] = '\0';
    }

    return ;
}


// 清空接收缓存
void esp8266_clear_recv_buff(void)
{
    esp8266_recv_info.recv_len = 0;
}


// 打印串口接收缓存中的信息
void esp8266_print_recv_buff(void)
{
    // 判断当前缓存是否为空
//    if (0 == esp8266_recv_info.recv_len)
//    {
//        printf("[%s] buff is empty!\r\n", __FUNCTION__);
//        return ;
//    }

    // 在缓存末尾“强制”手动增加一个字符串结束符，方便后面打印
    esp8266_recv_info.buff[ESP8266_RECV_BUFF_SIZE - 1] = '\0';
    printf("[%s] buff is\r\n%s\r\n", __FUNCTION__, esp8266_recv_info.buff);

    return ;
}


/*
 * esp8266 wifi透传模块初始化
 * 这里测死使用的是串口8，可以根据实际情况修改为其它串口
 * 注意龙芯1C300A没有串口8，龙芯1C300B才有串口5到串口11这几个串口
 */
void esp8266_init(void)
{
    unsigned int tx_gpio = 1;      // CAMDATA4/GPIO54/UART8_TX
    unsigned int rx_gpio = 0;      // CAMDATA5/GPIO55/UART8_RX

    // 设置引脚复用
    pin_set_remap(tx_gpio, PIN_REMAP_FOURTH);
    pin_set_remap(rx_gpio, PIN_REMAP_FOURTH);

    // 初始化串口
    esp8266_uart_info.UARTx     = LS1C_UART3;
    esp8266_uart_info.baudrate  = 115200;
    esp8266_uart_info.rx_enable = TRUE;
    uart_init(&esp8266_uart_info);

    // 设置中断处理函数
    irq_install(LS1C_UART3_IRQ, esp8266_uart_irqhandler, NULL);
    irq_enable(LS1C_UART3_IRQ);

    // 清空接收缓存
    esp8266_clear_recv_buff();
    printf("wifi_init_ok\r\n");
    return ;
}



/*
 * 通过串口发送数据给给esp8266
 * @buff 待发送的缓存
 * @len 待发送数据的长度，单位字节
 */
void esp8266_send(unsigned char *buff, unsigned int len)
{
    unsigned int i = 0;

    for ( i=0; i<len; i++)
    {
        uart_putc(esp8266_uart_info.UARTx, buff[i]);
    }

    return ;
}


/*
 * 发送字符串给ESP8266
 * @str
 */
void esp8266_send_str(unsigned char *str)
{
    esp8266_send((unsigned char *)str, strlen(str));

    return ;
}

void str_config(void)
{

return ;
}

/*
 * 测试esp8266 wifi模块（作为TCP客户端连接TCP服务器）
 */
void esp8266_sendtemp(void)
{
	char *temp_star = {"{\"method\":\"upload\",\"data\":[{\"Name\":\"01\",\"Value\":\""};
	strcat(temp_star,tems);
	strcat(temp_star,end);
    esp8266_send_str("{\"method\":\"update\",\"gatewayNo\":\"01\",\"userkey\":\"235d07123b074bcfa71109fbe32c3cc6\"}&^!\r\n");
    delay_s(2);
    esp8266_clear_recv_buff();
    esp8266_send_str(temp_star);

}

void esp8266_sendhumi(void)
{
	char *humi_star = {"{\"method\":\"upload\",\"data\":[{\"Name\":\"02\",\"Value\":\""};
//	const char *hend = {"\"}]}&^!"};

	strcat(humi_star,hums);
	strcat(humi_star,end);
    esp8266_send_str("{\"method\":\"update\",\"gatewayNo\":\"01\",\"userkey\":\"235d07123b074bcfa71109fbe32c3cc6\"}&^!\r\n");
    delay_s(2);
    esp8266_send_str(humi_star);
}

void esp8266_sendfire(void)
{
	char *fire_star = {"{\"method\":\"upload\",\"data\":[{\"Name\":\"03\",\"Value\":\""};

	strcat(fire_star,firewarn);
	strcat(fire_star,end);
    esp8266_send_str("{\"method\":\"update\",\"gatewayNo\":\"01\",\"userkey\":\"235d07123b074bcfa71109fbe32c3cc6\"}&^!\r\n");
    delay_s(2);
    esp8266_send_str(fire_star);
}

void esp8266_sendtemp4(void)
{
	char *du_star = {"{\"method\":\"upload\",\"data\":[{\"Name\":\"04\",\"Value\":\""};
	strcat(du_star,poisonwarn);
	strcat(du_star,end);
    esp8266_send_str("{\"method\":\"update\",\"gatewayNo\":\"01\",\"userkey\":\"235d07123b074bcfa71109fbe32c3cc6\"}&^!\r\n");
    delay_s(2);
    esp8266_clear_recv_buff();
    esp8266_send_str(du_star);

}

void esp8266_sendqiti(void)
{

	char *qiti_star = {"{\"method\":\"upload\",\"data\":[{\"Name\":\"04\",\"Value\":\""};

	strcat(qiti_star,poisonwarn);
	strcat(qiti_star,end);
	esp8266_send_str("{\"method\":\"update\",\"gatewayNo\":\"01\",\"userkey\":\"235d07123b074bcfa71109fbe32c3cc6\"}&^!\r\n");
	delay_s(2);
	esp8266_send_str(qiti_star);
//	char *qiti_star = {"{\"method\":\"upload\",\"data\":[{\"Name\":\"04\",\"Value\":\""};
//	strcat(qiti_star,poisonwarn);
//	strcat(qiti_star,end);
//	esp8266_send_str("{\"method\":\"update\",\"gatewayNo\":\"01\",\"userkey\":\"235d07123b074bcfa71109fbe32c3cc6\"}&^!\r\n");
//    delay_s(2);
//    esp8266_send_str(qiti_star);
}

void esp8266_config(void)
{
	esp8266_init();
	//  unsigned char i =1;

    // esp8266 wifi模块初始化
    /*if(i==1)
    {
    esp8266_init();

    printf("[%s] delay ... wait esp8266 init.\r\n", __FUNCTION__);
    delay_s(5);
//    esp8266_print_recv_buff();
    esp8266_clear_recv_buff();


    esp8266_send_str("AT+RST\r\n");
    delay_s(1);
    // 设置为1 station模式2 AP模式
    esp8266_send_str("AT+CWMODE=1\r\n");
    delay_s(1);
//    esp8266_print_recv_buff();
    esp8266_clear_recv_buff();
    //查询附件WiFi
//    esp8266_send_str("AT+CWLAP\r\n");
//    delay_s(10);
//    esp8266_print_recv_buff();
//    esp8266_clear_recv_buff();
    // 连接手机热点名称 密码
    esp8266_send_str("AT+CWJAP=\"Caesar\",\"11235813\"\r\n");
    delay_s(8);
//    esp8266_print_recv_buff();
    esp8266_clear_recv_buff();

    // 获取本地IP地址
//    esp8266_send_str("AT+CIFSR\r\n");
//    delay_s(3);
//    esp8266_print_recv_buff();
//    esp8266_clear_recv_buff();
*/
    // 设置单连接模式
//    delay_s(5);
//    delay_s(1);




    delay_s(1);
	esp8266_send_str("AT+CIPMUX=0\r\n");
    delay_s(1);
//    esp8266_print_recv_buff();
    esp8266_clear_recv_buff();

	esp8266_send_str("AT+CIPMODE=1\r\n");
	delay_s(2);
//	esp8266_print_recv_buff();
	esp8266_clear_recv_buff();
    //}

    // 建立TCP连接
	delay_s(1);
    esp8266_send_str("AT+CIPSTART=\"TCP\",\"tcp.lewei50.com\",9960\r\n");
    delay_s(3);
//    esp8266_print_recv_buff();
    esp8266_clear_recv_buff();

    // 发送数据
    esp8266_send_str("AT+CIPSEND\r\n");
    delay_s(2);
    esp8266_sendtemp4();
    delay_s(2);
    esp8266_sendfire();
    delay_s(2);
    esp8266_sendhumi();
    delay_s(2);
   esp8266_sendtemp();

    delay_s(2);




    delay_s(1);
    esp8266_send_str("+++");    // 结束透传

    delay_s(1);
    esp8266_clear_recv_buff();

    return ;
}
void esp8266_config2(void)
{
	esp8266_init();

	esp8266_send_str("AT+CIPMUX=0\r\n");
    delay_s(1);

	esp8266_send_str("AT+CIPMODE=1\r\n");

	delay_s(1);
    esp8266_send_str("AT+CIPSTART=\"TCP\",\"tcp.lewei50.com\",9960\r\n");
    delay_s(3);

    esp8266_send_str("AT+CIPSEND\r\n");
    delay_s(2);

   esp8266_sendtemp4();

    delay_s(2);




    delay_s(1);
    esp8266_send_str("+++");    // 结束透传

    delay_s(1);
    esp8266_clear_recv_buff();

    return ;
}


